package com.shuhan.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * --- 万物归集  不随你我 ---
 * <p>
 * 快捷短语
 * main ==  public static void main(String[] args);
 * sout ==  System.out.println();
 *
 * @author shuhan
 * @date 2025/4/2
 * @desc AOP增强注释
 */
@Component
@Aspect
public class MyAspect {

    @Pointcut("execution(* com.shuhan.service.impl.*.*(..))")
    public void myPointcut(){}

    // 前置增强
    @Before("myPointcut()")
    public void before(JoinPoint joinPoint) {

        System.out.println("前置增强/通知正在生效...");

        // 获得目标/执行方法所在类对象
        Object target = joinPoint.getTarget();
        System.out.println("target = " + target);

        // 获得目标/执行方法对象
        Class<? extends Signature> aClass = joinPoint.getSignature().getClass();
        System.out.println("aClass = " + aClass);

        // 获得目标/执行方法名
        String name = joinPoint.getSignature().getName();
        System.out.println("name = " + name);
    }

    // 后置增强
    @After("myPointcut()")
    public void after(JoinPoint joinPoint) {
        System.out.println("后置增强/通知生效...");
    }

    // 环绕增强
    @Around("myPointcut()")
    public void around(ProceedingJoinPoint joinPoint){
        System.out.println("------开启事务------");

        try {
            joinPoint.proceed();
            System.out.println("------无异常，提交事务------");
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("------异常，异常，异常------");
        }
    }

    // 后置异常增强
    @AfterThrowing(value = "myPointcut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e){

        System.out.println("错误！错误！错误！" + e);

    }

    // 后置返回增强
    @AfterReturning(value = "myPointcut()",returning = "ret")
    public void afterReturn(Object ret){

        System.out.println("此方法的返回值是" + ret);
    }
}
